import {computed, ref, Ref, unref} from "vue";
import {Pagination, Sorting, Activity, Prize} from "../types";
import {useActivityStore} from "../store/activity";
import {usePrizeStore} from "../store/prize";

const makePaginationRef = () => ref<Pagination>({ page: 1, perPage: 10, total: 0 })
const makeSortingRef = () => ref<Sorting>({ sortBy: 'created_at', sortingOrder: 'desc' })

export const useListPage =  (options?: { sorting?: Ref<Sorting>; pagination?: Ref<Pagination> }) => {

  const {sorting = makeSortingRef(), pagination = makePaginationRef()} = options ?? {}
  const isLoading = ref(false)

  const activityStore = useActivityStore();
  const prizeStore = usePrizeStore();

  const fetch = async () => {
    await activityStore.getPage({
      sorting: unref(sorting),
      pagination: unref(pagination),
    })
  }

  fetch()

  const createActivity = async (activity: Activity)=> {
    await activityStore.createActivity(activity)
    await fetch()
  }

  const recruiting = async (activity: Activity)=> {
    await activityStore.recruiting(activity.id)
    await fetch()
  }

  const activeActivity = async (activity: Activity)=> {
    await activityStore.activeActivity(activity.id)
    await fetch()
  }
  const createPrize = async (prize: Prize) => {
    await prizeStore.createPrize(prize);
    await fetch()
  }

  const dataList = computed(() => {
    return activityStore.items as Activity[]
  });

  return {
    fetch,
    createActivity,
    recruiting,
    activeActivity,
    createPrize,
    dataList,
    isLoading,
    sorting,
    pagination
  }
}
